package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {
    @Autowired
    private Configuration configuration;
    @Resource(name = "minIOFileStorageService")
    private FileStorageService fileStorageService;
    @Value("${file.minio.prefix}")
    private String prefix;
    @Autowired
    ApArticleMapper apArticleMapper;
    @Resource
    AuthorMapper authorMapper;

    @Value("${file.minio.readPath}")
    private String readPath;

    /**
     * 生成文章静态页面
     */
    @Override
    public void generateArticlePage(String content, ApArticle apArticle) {
        //1.获取文章内容
        try {
            Template template = configuration.getTemplate("article.ftl");

            // 2. 准备数据模型: authorApUserId article content
            HashMap<Object, Object> params = new HashMap<>();
            params.put("article", apArticle);
            // jSON类型的数组字符串 -> List<Map>
            params.put("content", JSON.parseArray(content, Map.class));
            ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
            if (apAuthor == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "" +
                        "id为" + apArticle.getAuthorId() + "的作者不存在");
            }
            // 作者对应的用户ID
            params.put("authorApUserId", apAuthor.getUserId());
            // 3. 使用数据替换模板，== 输出到StringWriter
            StringWriter stringWriter = new StringWriter();
            // 将模板 + 数据 的输出内容字符串存入到StringWriter
            template.process(params, stringWriter);
            String htmlStr = stringWriter.toString();

            // 4. 封装输入流，字节数组输出流
            ByteArrayInputStream inputStream = new ByteArrayInputStream(htmlStr.getBytes());
            // 5. 将静态页内容上传到MinIO中
            String staticPath = fileStorageService.store(prefix, apArticle.getId() + ".html",
                    "text/html", inputStream);
            // 6. 修改文章static_url 静态页路径
            apArticle.setStaticUrl(staticPath);
            //  7. 更新数据库文章的静态页路径
            apArticleMapper.updateById(apArticle);
            // 8. 打印静态页路径通过log对象
            log.info("生成文章静态页路径为: {}", readPath + staticPath);

        } catch (IOException e) {
            e.printStackTrace();
            log.error("生成文章静态页失败：原因：{}, 请检查模板是否存在", e.getMessage() );
        } catch (TemplateException e) {
            e.printStackTrace();
            log.error("生成文章静态页失败：原因：{}, 请检查 模板语法 或 数据模型 是否存在",  e.getMessage() );
        }

    }
}